package com.szgz.platform.controller;

import com.szgz.platform.model.UserFile;
import com.szgz.platform.service.UserFileService;
import com.szgz.platform.result.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 用户文件管理控制器
 */
@RestController
@RequestMapping("/api/user-files")
@CrossOrigin(origins = "*")
public class UserFileController {
    
    private static final Logger logger = LoggerFactory.getLogger(UserFileController.class);
    
    @Autowired
    private UserFileService userFileService;
    
    /**
     * 获取用户的所有文件列表
     */
    @GetMapping("/{userId}")
    public ResponseEntity<ApiResponse<List<UserFile>>> getUserFiles(@PathVariable String userId) {
        try {
            logger.info("Getting files for user: {}", userId);
            List<UserFile> files = userFileService.getUserFiles(userId);
            return ResponseEntity.ok(ApiResponse.success(files));
        } catch (Exception e) {
            logger.error("Error getting files for user: {}", userId, e);
            return ResponseEntity.internalServerError().body(ApiResponse.fail("获取文件列表失败"));
        }
    }
    
    /**
     * 获取用户指定目录下的文件
     */
    @GetMapping("/{userId}/directory")
    public ResponseEntity<ApiResponse<List<UserFile>>> getUserFilesInDirectory(
            @PathVariable String userId,
            @RequestParam(defaultValue = "/home/coder/project") String directory) {
        try {
            logger.info("Getting files in directory {} for user: {}", directory, userId);
            List<UserFile> files = userFileService.getUserFilesInDirectory(userId, directory);
            return ResponseEntity.ok(ApiResponse.success(files));
        } catch (Exception e) {
            logger.error("Error getting files in directory for user: {}", userId, e);
            return ResponseEntity.internalServerError().body(ApiResponse.fail("获取目录文件失败"));
        }
    }
    
    /**
     * 获取用户的项目列表
     */
    @GetMapping("/{userId}/projects")
    public ResponseEntity<ApiResponse<List<UserFile>>> getUserProjects(@PathVariable String userId) {
        try {
            logger.info("Getting projects for user: {}", userId);
            List<UserFile> projects = userFileService.getUserProjects(userId);
            return ResponseEntity.ok(ApiResponse.success(projects));
        } catch (Exception e) {
            logger.error("Error getting projects for user: {}", userId, e);
            return ResponseEntity.internalServerError().body(ApiResponse.fail("获取项目失败"));
        }
    }
    
    /**
     * 获取文件内容
     */
    @GetMapping("/{userId}/file")
    public ResponseEntity<ApiResponse<String>> getFileContent(
            @PathVariable String userId,
            @RequestParam String filePath) {
        try {
            logger.info("Getting file content for user: {}, file: {}", userId, filePath);
            String content = userFileService.getFileContent(userId, filePath);
            return ResponseEntity.ok(ApiResponse.success(content));
        } catch (Exception e) {
            logger.error("Error getting file content for user: {}", userId, e);
            return ResponseEntity.internalServerError().body(ApiResponse.fail("获取文件内容失败"));
        }
    }
    
    /**
     * 搜索用户文件
     */
    @GetMapping("/{userId}/search")
    public ResponseEntity<ApiResponse<List<UserFile>>> searchUserFiles(
            @PathVariable String userId,
            @RequestParam String query,
            @RequestParam(defaultValue = "name") String searchType) {
        try {
            logger.info("Searching files for user: {}, query: {}", userId, query);
            List<UserFile> results = userFileService.searchUserFiles(userId, query, searchType);
            return ResponseEntity.ok(ApiResponse.success(results));
        } catch (Exception e) {
            logger.error("Error searching files for user: {}", userId, e);
            return ResponseEntity.internalServerError().body(ApiResponse.fail("搜索失败"));
        }
    }

    /**
     * 上传单个文件到 IDE 容器
     */
    @PostMapping(path = "/{userId}/upload", consumes = {"multipart/form-data"})
    public ResponseEntity<ApiResponse<java.util.Map<String, Object>>> uploadFileToIde(
            @PathVariable String userId,
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "targetDirectory", required = false, defaultValue = "/home/coder/project") String targetDirectory) {
        try {
            String dest = userFileService.uploadFileToIde(userId, file, targetDirectory);
            return ResponseEntity.ok(ApiResponse.success(java.util.Map.of("path", dest)));
        } catch (Exception e) {
            logger.error("Upload failed for user {}: {}", userId, e.getMessage());
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }

    /**
     * 批量上传文件到 IDE 容器
     */
    @PostMapping(path = "/{userId}/upload/batch", consumes = {"multipart/form-data"})
    public ResponseEntity<ApiResponse<java.util.Map<String, Object>>> uploadFilesToIde(
            @PathVariable String userId,
            @RequestParam("files") List<MultipartFile> files,
            @RequestParam(value = "targetDirectory", required = false, defaultValue = "/home/coder/project") String targetDirectory) {
        try {
            List<String> dests = userFileService.uploadFilesToIde(userId, files, targetDirectory);
            return ResponseEntity.ok(ApiResponse.success(java.util.Map.of("paths", dests)));
        } catch (Exception e) {
            logger.error("Batch upload failed for user {}: {}", userId, e.getMessage());
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }
    
    /**
     * 获取用户的文件树结构
     */
    @GetMapping("/{userId}/tree")
    public ResponseEntity<ApiResponse<List<UserFileService.FileTreeNode>>> getUserFileTree(
            @PathVariable String userId,
            @RequestParam(defaultValue = "/home/coder/project") String rootDirectory) {
        try {
            logger.info("Getting file tree for user: {} in directory: {}", userId, rootDirectory);
            List<UserFileService.FileTreeNode> tree = userFileService.getUserFileTree(userId, rootDirectory);
            return ResponseEntity.ok(ApiResponse.success(tree));
        } catch (Exception e) {
            logger.error("Error getting file tree for user: {}", userId, e);
            return ResponseEntity.internalServerError().body(ApiResponse.fail("获取文件树失败"));
        }
    }
    
    /**
     * 获取文件统计信息
     */
    @GetMapping("/{userId}/stats")
    public ResponseEntity<ApiResponse<UserFileService.UserFileStats>> getUserFileStats(@PathVariable String userId) {
        try {
            logger.info("Getting file stats for user: {}", userId);
            UserFileService.UserFileStats stats = userFileService.getUserFileStats(userId);
            return ResponseEntity.ok(ApiResponse.success(stats));
        } catch (Exception e) {
            logger.error("Error getting file stats for user: {}", userId, e);
            return ResponseEntity.internalServerError().body(ApiResponse.fail("获取统计失败"));
        }
    }

    /**
     * 保存文件内容到 IDE 容器
     */
    @PostMapping("/{userId}/save")
    public ResponseEntity<ApiResponse<java.util.Map<String, Object>>> saveFile(
            @PathVariable String userId,
            @RequestParam String filePath,
            @RequestBody String content) {
        try {
            boolean ok = userFileService.saveFileContent(userId, filePath, content);
            return ResponseEntity.ok(ApiResponse.success(java.util.Map.of("success", ok)));
        } catch (Exception e) {
            logger.error("Save file failed for user {} path {}", userId, filePath, e);
            return ResponseEntity.badRequest().body(ApiResponse.fail(e.getMessage()));
        }
    }

    /**
     * 新建空文件
     */
    @PostMapping("/{userId}/create-file")
    public ResponseEntity<ApiResponse<java.util.Map<String, Object>>> createFile(
            @PathVariable String userId,
            @RequestParam String filePath) {
        boolean ok = userFileService.createFile(userId, filePath);
        return ResponseEntity.ok(ApiResponse.success(java.util.Map.of("success", ok)));
    }

    /**
     * 新建目录（递归）
     */
    @PostMapping("/{userId}/create-directory")
    public ResponseEntity<ApiResponse<java.util.Map<String, Object>>> createDirectory(
            @PathVariable String userId,
            @RequestParam String dirPath) {
        boolean ok = userFileService.createDirectory(userId, dirPath);
        return ResponseEntity.ok(ApiResponse.success(java.util.Map.of("success", ok)));
    }

    /**
     * 删除文件或目录
     */
    @DeleteMapping("/{userId}/delete")
    public ResponseEntity<ApiResponse<java.util.Map<String, Object>>> deletePath(
            @PathVariable String userId,
            @RequestParam String path,
            @RequestParam(defaultValue = "true") boolean recursive) {
        boolean ok = userFileService.deletePath(userId, path, recursive);
        return ResponseEntity.ok(ApiResponse.success(java.util.Map.of("success", ok)));
    }
} 